package org.sshbot;

import java.net.URL;
import java.util.Locale;
import java.util.Properties;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.securecrt.AppDetail;
import com.securecrt.SaveSession;
import com.securecrt.pojo.PropertiesHelper;

public class AutoUpdateNewVersion extends Activity {

	public static String URL_LIST_PRODUCT = "";
	private static Properties properties;
	TextView verson; 
	Double currentVersionName=0.0;
	String curDescription="",curpkg="",cursize="",curlink="";
	Double curversionCode=0.0;
	Double newVersionName=0.0;
	private Handler mHandler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		//Get URL_LIST_PRODUCT
		if(URL_LIST_PRODUCT == null || "".equals(URL_LIST_PRODUCT)){
				URL_LIST_PRODUCT = getUrl(this.getApplicationContext());
		}
				
		setContentView(R.layout.autoupdatenewversion);
		CheckNewVersion();
	}
	
	private String getUrl(Context context){
		if (properties == null){
				properties = PropertiesHelper.loadProperties(context);
	    }
		return properties.getProperty(PropertiesHelper.URL_LIST_PRODUCT);
	}
	
	private boolean aaaa(){
		ConnectivityManager connectivityManager =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
	}
	private void checkNetwork(){
//		if(haveNetworkConnection())
//			System.out.println("111111");
//		else
//			System.out.println("222222");
//		CheckConnectivity check=new CheckConnectivity();
//		Boolean conn=check.checkNow(this);
//		if(CheckConnectivity.getInstance(this).isOnline(this)){
//			CheckNewVersion();System.out.println("111111");
//		}else{
//			connectivityMessage();System.out.println("2222222");
//		}
		if(aaaa())
			System.out.println("111111");
		else
			System.out.println("22222");
	}
	private void callback_try(){
        Intent i=new Intent(this, AutoUpdateNewVersion.class);
        startActivity(i);
	}
//	private void tryAgain(){
//		final ProgressDialog pro1=ProgressDialog.show(this, "", getString(R.string.waiting)+"...");
//		Thread t=new Thread(new Runnable() {
//			@Override
//			public void run() {
//				callback_try();
//				pro1.dismiss();
//			}
//			}
//		);t.start();
//	}
	private void connectivityMessage(){
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		final AlertDialog alertDialog;
		Context mContext=getApplicationContext();
		LayoutInflater inflater=(LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout=inflater.inflate(R.layout.checknetwork, (ViewGroup) findViewById(R.id.checkconnection));
		builder.setView(layout);
		alertDialog=builder.create();
		
		Button btok=(Button)layout.findViewById(R.id.bttry);
		btok.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				alertDialog.dismiss();
				callback_try();
			}
		});
		Button btcancel=(Button)layout.findViewById(R.id.btcancel);
		btcancel.setOnClickListener(new Button.OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
				alertDialog.dismiss();
				System.exit(0);
			}
		});
		alertDialog.show();
	}
//	private void CheckNewVersion(){
//		verson = (TextView)findViewById(R.id.tvVersion);
//		verson.setText("Verson "+getSoftwareVersion());
//<<<<<<< .mine
//=======
//		setLocale("en");
//	}
	private void setLocale(String localeCode){
	    Locale locale = new Locale(localeCode);
	    Locale.setDefault(locale);
	    Configuration config = new Configuration();
	    config.locale = locale;
	    getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
	}
	private void CheckNewVersion(){
		verson = (TextView)findViewById(R.id.tvVersion);
		verson.setText("Verson "+getSoftwareVersion());
		getProductname();
		currentVersionName=Double.parseDouble(getSoftwareVersion());
		if(newVersionName>currentVersionName && getProductname().equalsIgnoreCase(getResources().getString(R.string.app_name))){
        	showDialogUpdateNewVersion();
		}
		else{
			mHandler.postDelayed(passContext, 3000);
		}
	}
	
	private void showDialogUpdateNewVersion(){
		final Dialog dialog=new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		Context mContext=getApplicationContext();
		LayoutInflater inflater=(LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout=inflater.inflate(R.layout.autoupdatealertdialog, (ViewGroup) findViewById(R.id.confirmconnection));
		dialog.setContentView(layout);
		Button btok=(Button)layout.findViewById(R.id.btok);
		btok.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		btok.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				loadList1();
			}
		});
		Button btcancel=(Button)layout.findViewById(R.id.btcancel);
		btcancel.setBackgroundDrawable(getResources().getDrawable(R.drawable.btcancelstatus));
		btcancel.setOnClickListener(new Button.OnClickListener() {			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				passContext1();
			}
		});
		dialog.show();
    }

	private void loadList1(){
		final ProgressDialog pro=ProgressDialog.show(this, "", getString(R.string.waiting)+"...");
		Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				loadList();
				pro.dismiss();
			}
			}
		);t.start();
	}
	private void loadList() {
		String[] item = {getProductname() ,"",curDescription,curlink,cursize,newVersionName.toString()};
		Intent intent=new Intent(this, AppDetail.class);
		intent.putExtra("item", item);
		intent.putExtra("pkg", curpkg);
		intent.putExtra("verCode", curversionCode);
		startActivity(intent);
	}
	private String getSoftwareVersion(){
		String vsname="";
		try{
			PackageInfo pinfo=getPackageManager().getPackageInfo(getPackageName(), 0);
			vsname= pinfo.versionName;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return vsname;
	}
	private Runnable passContext = new Runnable() {
		@Override
		public void run() {
			passContext();
		}
	};
	private void passContext1(){
		final ProgressDialog pro=ProgressDialog.show(this, "", getString(R.string.waiting)+"...");
		Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				passContext();
				pro.dismiss();
			}
			}
		);t.start();
	}
	private void passContext() {
		Intent i=new Intent(this,SaveSession.class);
		i.putExtra("host","");
		i.putExtra("port", "");
		i.putExtra("user", "");
		i.putExtra("pass", "");
		startActivity(i);
	}
	private String getProductname(){
		String nameCurrent="";
		try{
			XmlPullParser xmlPullParser = Xml.newPullParser();
			URL url = new URL(URL_LIST_PRODUCT);
			xmlPullParser.setInput(url.openStream(), "UTF-8");
			int eventType;
			Double versionCode=0.0;
			String name="",version="",description="",pkg="",size="",link="";
			while ((eventType = xmlPullParser.next()) != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xmlPullParser.getName().equals("name")) {
						name = xmlPullParser.nextText();
						if(name.equalsIgnoreCase(getResources().getString(R.string.app_name))){
							nameCurrent=name;
						}
					}else if (xmlPullParser.getName().equals("package")) {
						pkg = xmlPullParser.nextText();
						if(name.equalsIgnoreCase(getResources().getString(R.string.app_name))){
							curpkg=pkg;
						}
					} else if (xmlPullParser.getName().equals("size")) {
						size = xmlPullParser.nextText();
						if(name.equalsIgnoreCase(getResources().getString(R.string.app_name))){
							cursize=size;
						}
					}else if (xmlPullParser.getName().equals("version")) {
						version = xmlPullParser.nextText();
						if(name.equalsIgnoreCase(getResources().getString(R.string.app_name))){
							versionCode=Double.parseDouble(version);
							curversionCode=versionCode;
							if(newVersionName<versionCode)
								newVersionName=versionCode;
						}
					}else if (xmlPullParser.getName().equals("link")) {
						link = xmlPullParser.nextText();
						if(name.equalsIgnoreCase(getResources().getString(R.string.app_name))){curlink=link;}
					}else if (xmlPullParser.getName().equals("description")) {
						description = xmlPullParser.nextText();
						if(name.equalsIgnoreCase(getResources().getString(R.string.app_name))){
							curDescription=description;
						}
					}
				}
			}
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		return nameCurrent;
	}

}
